package com.auto.autoapp.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityAccountRaiseSettingBinding
import com.auto.autoapp.model.AccountRaiseSetting
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.task.AccountRaiseTask
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SettingItemView
import com.auto.autoapp.widgets.SimpleToolbar
import com.ven.assists.stepper.StepManager

class AccountRaiseSettingActivity : BaseActivity() {
    private lateinit var binding: ActivityAccountRaiseSettingBinding
    private var keyboardVisible: Boolean = false
    override fun provideView(): View {
        binding = ActivityAccountRaiseSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle(intent.getStringExtra("title"))
    }


    override fun onInit() {
        // 展示已保存配置（统一 JSON 对象读取）
        val cfg = SpUtil.getAccountRaiseSetting()
        binding.sivKeywords.setValues(listOf(cfg.keyword))
        binding.sivCollectCount.setValues(listOf(cfg.collectCount.toString()))
        binding.sivBrowseDuration.setValues(listOf(cfg.browseDurationSeconds.toString()))
        binding.sivLikeProbability.setValues(listOf(cfg.likeProbability.toString()))
        binding.sivCommentProbability.setValues(listOf(cfg.commentProbability.toString()))
        binding.sivCommentContent.setValues(cfg.commentContentList)

        // 确认保存
        binding.btnConfirm.setOnClickListener {
            // 取值
            val kw = binding.sivKeywords.getValues().firstOrNull()?.trim().orEmpty()
            val collectStr = binding.sivCollectCount.getValues().firstOrNull()?.trim().orEmpty()
            val browseStr = binding.sivBrowseDuration.getValues().firstOrNull()?.trim().orEmpty()
            val likeStr = binding.sivLikeProbability.getValues().firstOrNull()?.trim().orEmpty()
            val commentStr =
                binding.sivCommentProbability.getValues().firstOrNull()?.trim().orEmpty()
            val commentContents =
                binding.sivCommentContent.getValues().map { it.trim() }.filter { it.isNotEmpty() }

            // 清除旧错误
            binding.sivKeywords.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error = null
            binding.sivCollectCount.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                null
            binding.sivBrowseDuration.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                null
            binding.sivLikeProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                null
            binding.sivCommentProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                null

            var hasError = false

            if (kw.isBlank()) {
                binding.sivKeywords.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入关键字"
                hasError = true
            }


            val collectCounts = collectStr.toIntOrNull() ?: -1
            if (collectCounts <= 0) {
                binding.sivCollectCount.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的整数"
                hasError = true
            }


            val browseSeconds = browseStr.toIntOrNull() ?: -1
            if (browseSeconds <= 0) {
                binding.sivBrowseDuration.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的整数秒数"
                hasError = true
            }

            val likePercent = likeStr.toIntOrNull()
            if (likePercent == null || likePercent !in 0..100) {
                binding.sivLikeProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入 0-100 的整数"
                hasError = true
            }

            val commentPercent = commentStr.toIntOrNull()
            if (commentPercent == null || commentPercent !in 0..100) {
                binding.sivCommentProbability.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入 0-100 的整数"
                hasError = true
            }

            if ((commentPercent ?: 0) > 0 && commentContents.isEmpty()) {
                binding.sivCommentContent.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入至少一条评论内容"
                hasError = true
            }

            if (hasError) {
                Toast.makeText(this, "请修正标红项后再确认", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            SpUtil.setAccountRaiseSetting(
                AccountRaiseSetting(
                    keyword = kw,
                    browseDurationSeconds = browseSeconds,
                    likeProbability = likePercent!!,
                    commentProbability = commentPercent!!,
                    collectCount = collectCounts,
                    commentContentList = commentContents,
                )
            )


            if (FloatingWindowService.getInstance() == null) {
                val intent = Intent(this, FloatingWindowService::class.java)
                intent.action = "SHOW_FLOATING_WINDOW"
                startService(intent)
            }

            StepManager.isStop = true
            StepManager.execute(AccountRaiseTask::class.java, 1, begin = true)
        }
    }

    private fun attachFocusScroll(item: SettingItemView) {
        item.setOnChildFocusListener { target ->
            scrollToView(target)
        }
    }

    private fun scrollToView(target: View) {
        // 将目标视图的矩形转换到 ScrollView 坐标系，并滚动到其顶部附近
        binding.scrollContent.post {
            val rect = Rect()
            target.getDrawingRect(rect)
            binding.scrollContent.offsetDescendantRectToMyCoords(target, rect)
            val y = (rect.top - dp(24)).coerceAtLeast(0)
            binding.scrollContent.smoothScrollTo(0, y)
        }
    }

    private fun dp(value: Int): Int {
        val d = resources.displayMetrics.density
        return (value * d).toInt()
    }


}